package com.foot.travel.activity;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.foot.travel.R;
import com.foot.travel.event.NetRefreshEvent;
import com.koalac.ironman.common.module.ModuleActivity;
import com.koalac.ironman.net.MyRequest;
import com.koalac.ironman.net.ResponseCallback;
import com.koalac.ironman.net.pojo.request.CGetSchoolTravelDetail;
import com.koalac.ironman.net.pojo.request.ClientProtocolBase;
import com.koalac.ironman.net.pojo.request.GetAdviseDetail;
import com.koalac.ironman.net.pojo.request.GetSchoolServiceDetail;
import com.koalac.ironman.net.pojo.response.GoodPicture;
import com.koalac.ironman.net.pojo.response.Response;
import com.koalac.ironman.net.pojo.response.SchoolServiceDetail;
import com.koalac.ironman.net.pojo.response.SchoolTravelDetail;
import com.koalac.ironman.util.ScreenInfoUtil;
import com.koalac.ironman.util.StringUtils;
import com.koalac.ironman.util.WeakHandler;
import com.koalac.ironman.viewhelper.ViewInject;
import com.koalac.ironman.widget.ImageLoadAgreement.ImageType;
import com.koalac.ironman.widget.LifeqImageView;
import com.koalac.ironman.widget.LoadingDialog;
import com.shizhefei.view.indicator.FixedIndicatorView;
import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.IndicatorViewPager.IndicatorPagerAdapter;
import com.shizhefei.view.indicator.IndicatorViewPager.IndicatorViewPagerAdapter;
import com.squareup.otto.Subscribe;

public class SchoolTravelDetailActivity extends ModuleActivity implements OnClickListener {

	CGetSchoolTravelDetail mCGetSchoolTravelDetail;
	GetAdviseDetail mGetAdviseDetaill;
	private String mSchoolTravelDetailId;
	SchoolTravelDetail mSchoolTravelDetail;
	public static final String SCHOOL_TRAVEL_DETAIL_ID = "school_travel_detail_id";
	@ViewInject(id = R.id.parent_layout)
	View mParentLayout;
	@ViewInject(id = R.id.guide_viewPager)
	ViewPager mGuideViewPager;
	@ViewInject(id = R.id.guide_indicator_layout)
	LinearLayout mGuideIndicatorLayout;

	@ViewInject(id = R.id.travel_name)
	TextView mTravelNameView;
	@ViewInject(id = R.id.place)
	TextView mPlaceView;

	@ViewInject(id = R.id.thirty_seat, click = "onClick")
	TextView mThirtyView;
	@ViewInject(id = R.id.fourty_seat, click = "onClick")
	TextView mFourtyView;
	@ViewInject(id = R.id.fifty_seat, click = "onClick")
	TextView mFifityView;

	@ViewInject(id = R.id.original_price)
	TextView mOriginalPriceView;
	@ViewInject(id = R.id.discount)
	TextView mDiscountView;
	@ViewInject(id = R.id.preferential_price)
	TextView mPreferentialPriceView;

	@ViewInject(id = R.id.explain)
	TextView mExplainView;
	@ViewInject(id = R.id.date)
	TextView mDateView;

	@ViewInject(id = R.id.outline, click = "onClick")
	TextView mOutlineView;
	@ViewInject(id = R.id.cost, click = "onClick")
	TextView mCostView;
	@ViewInject(id = R.id.rule_description, click = "onClick")
	TextView mRuleDescriptionView;
	@ViewInject(id = R.id.content)
	WebView mContentView;

	@ViewInject(id = R.id.qq_icon, click = "onClick")
	ImageView mQQIconView;
	@ViewInject(id = R.id.phone_icon, click = "onClick")
	ImageView mPhoneIcon;
	@ViewInject(id = R.id.place_next_btn, click = "onClick")
	TextView mPlaceNextBtn;
	@ViewInject(id = R.id.date, click = "onClick")
	TextView mDateBtn;
	private LayoutInflater mInflater;
	private ArrayList<String> mCoverImageUrlList;

	private LoadingDialog mLoadingDialog;
	private SchoolServiceDetail mSchoolServiceDetail;
	private double mSelectPrice;

	private String mDate;
	private static final int QUEST_DATE_CODE = 1 << 0;
	public static final String HOT_RECOMMENT = "hot_recomment";
	

	private ScheduledExecutorService mScheduledExecutorService;
	private int mCurrentItem;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setNavigationTitle("产品详情");
		mParentLayout.setVisibility(View.GONE);
		mInflater = LayoutInflater.from(getApplicationContext());
		setBackButtonVisibility(true);
		setGuideViewPagerHeight();
		getSchoolTravelDetail();
	}

	@Override
	protected void onResume() {
		super.onResume();
		super.onStart();
		mScheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
		// 每隔2秒钟切换一张图片
		mScheduledExecutorService.scheduleWithFixedDelay(new ViewPagerTask(), 3, 3, TimeUnit.SECONDS);
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (!mScheduledExecutorService.isShutdown()) {
			mScheduledExecutorService.shutdown();
		}
	}

	// 切换图片
		private class ViewPagerTask implements Runnable {

			@Override
			public void run() {
				mCurrentItem = mGuideViewPager.getCurrentItem();
				mCurrentItem++;
				// 更新界面
				handler.obtainMessage().sendToTarget();
			}
		}

	private WeakHandler<SchoolTravelDetailActivity> handler = new WeakHandler<SchoolTravelDetailActivity>(
			SchoolTravelDetailActivity.this) {

		@Override
		protected void processMessage(SchoolTravelDetailActivity activity, Message msg) {
			// 设置当前页面
			mGuideViewPager.setCurrentItem(mCurrentItem, true);
		}
	};

	private void initDescriptionLayout() {
		setmContentView(R.id.outline, mSchoolTravelDetail.getMessage());
	}

	private void getSchoolTravelDetail() {
		ClientProtocolBase clientProtocolBase;
		if (getIntent().getBooleanExtra(HOT_RECOMMENT, false)) {
			mGetAdviseDetaill = new GetAdviseDetail();
			mGetAdviseDetaill.setId(getIntent().getStringExtra(SCHOOL_TRAVEL_DETAIL_ID));
			clientProtocolBase = mGetAdviseDetaill;
		} else {
			mCGetSchoolTravelDetail = new CGetSchoolTravelDetail();
			mCGetSchoolTravelDetail.setId(getIntent().getStringExtra(SCHOOL_TRAVEL_DETAIL_ID));
			clientProtocolBase = mCGetSchoolTravelDetail;
		}

		mLoadingDialog = showLoadingDialog("获取产品详情...");
		MyRequest.request(SchoolTravelDetailActivity.this, clientProtocolBase, new ResponseCallback() {

			@Override
			public void process(boolean result, Context context, Response data, String msg) {
				if (result) {
					mParentLayout.setVisibility(View.VISIBLE);
					mSchoolTravelDetail = data.getObject(SchoolTravelDetail.class);

					mSchoolTravelDetail.setMinFollowNumber(1);
					mSchoolTravelDetail.setMaxFollowNumber(30);

					initCoverImageUrlList(mSchoolTravelDetail.getGoodPictureList());
					mTravelNameView.setText(mSchoolTravelDetail.getName());
					mPlaceView.setText(mSchoolTravelDetail.getStartPlace());
					mExplainView.setText(mSchoolTravelDetail.getRemark());
					/**
					 * 原价
					 */
					setPriceLayout(R.id.thirty_seat, mSchoolTravelDetail.getThirtyPrice());
					/**
					 * 初始化概要 费用 规则
					 */
					initDescriptionLayout();
					getSchoolServiceDetail();
					    setNetworkVisibility(false);
				}else {
				    setNetworkVisibility(true);
				}
			}
		});
	}
	
	@Subscribe
	    public void onRefresh(NetRefreshEvent netRefreshEvent) {
		setNetworkVisibility(false);
		getSchoolTravelDetail();
	    }
	
	private void getSchoolServiceDetail() {
		GetSchoolServiceDetail getSchoolServiceDetail = new GetSchoolServiceDetail();
		MyRequest.request(SchoolTravelDetailActivity.this, getSchoolServiceDetail, new ResponseCallback() {

			@Override
			public void process(boolean result, Context context, Response data, String msg) {
				canceledLoadingDialog(mLoadingDialog);
				if (result) {
					mSchoolServiceDetail = data.getObject(SchoolServiceDetail.class);
				}
			}
		});
	}

	private void setPriceLayout(int viewID, int discountPrice) {
		mSelectPrice = discountPrice;
		mOriginalPriceView.setText("¥" + mSchoolTravelDetail.getBeforePrice());
		mOriginalPriceView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
		mPreferentialPriceView.setText("¥" + discountPrice);
		double discount = ((double) discountPrice) / ((double) mSchoolTravelDetail.getBeforePrice()) * 10;

		NumberFormat nf = new DecimalFormat("0.0");
		discount = Double.parseDouble(nf.format(discount));
		mDiscountView.setText("" + (discount) + "折");
		mThirtyView.setSelected(viewID == R.id.thirty_seat);
		mFourtyView.setSelected(viewID == R.id.fourty_seat);
		mFifityView.setSelected(viewID == R.id.fifty_seat);

		int white = getResources().getColor(R.color.white);
		int aboutText = getResources().getColor(R.color.about_text);

		mThirtyView.setTextColor(viewID == R.id.thirty_seat ? white : aboutText);
		mFourtyView.setTextColor(viewID == R.id.fourty_seat ? white : aboutText);
		mFifityView.setTextColor(viewID == R.id.fifty_seat ? white : aboutText);
	}

	@SuppressWarnings("deprecation")
	private void initCoverImageUrlList(List<GoodPicture> homePictureList) {
	    if (homePictureList.size() == 0) {
		return;
	    }
		mCoverImageUrlList = new ArrayList<String>();
		for (GoodPicture goodPicture : homePictureList) {
			mCoverImageUrlList.add(goodPicture.getHeadImgUrl());
		}
		mGuideViewPager.setAdapter(pagerAdapter);
		mGuideViewPager.setCurrentItem(mCoverImageUrlList.size() * 100, false);
		pagerAdapter.notifyDataSetChanged();
		setUpGuideIndicatorLayout(mGuideIndicatorLayout);
		mGuideViewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				int size = mGuideIndicatorLayout.getChildCount();
				for (int i = 0; i < size; i++) {
					View indicator = mGuideIndicatorLayout.getChildAt(i);
					indicator.setSelected(false);
				}
				mGuideIndicatorLayout.getChildAt(position % mCoverImageUrlList.size()).setSelected(true);
				;
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});
	}
	
	PagerAdapter pagerAdapter = new PagerAdapter() {

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		public Object instantiateItem(ViewGroup container, int position) {
			View convertView = mInflater.inflate(R.layout.image_home_layout, container, false);
			((LifeqImageView) convertView.findViewById(R.id.image)).loadFile(
					mCoverImageUrlList.get(position % mCoverImageUrlList.size()), ImageType.SourceImage, null, null);
			container.addView(convertView);
			return convertView;
		}

		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}

		@Override
		public int getCount() {
			return Integer.MAX_VALUE;
		}
	};

	private void setUpGuideIndicatorLayout(LinearLayout guideIndicatorLayout) {
	    guideIndicatorLayout.removeAllViews();
		int indicatorSize = ScreenInfoUtil.dp2px(SchoolTravelDetailActivity.this, 10);
		for (int i = 0; i < mCoverImageUrlList.size(); i++) {
			View indicator = mInflater.inflate(R.layout.tab_guide, null);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(indicatorSize, indicatorSize);
			lp.setMargins(0, 0, indicatorSize, 0);
			indicator.setLayoutParams(lp);
			guideIndicatorLayout.addView(indicator);
		}
	}

	private void setGuideViewPagerHeight() {
		int height = ScreenInfoUtil.getScreenWidth(SchoolTravelDetailActivity.this) / 2;
		RelativeLayout.LayoutParams layoutParams = (android.widget.RelativeLayout.LayoutParams) mGuideViewPager
				.getLayoutParams();
		layoutParams.height = height;
		mGuideViewPager.setLayoutParams(layoutParams);
	}

	@Override
	protected void initLayout(ViewGroup rootContentView) {
		addContentView(R.layout.activity_school_travel_detail);
	}

	@Override
	public void onClick(View v) {
		int viewId = v.getId();
		switch (viewId) {
		case R.id.thirty_seat:
			setPriceLayout(R.id.thirty_seat, mSchoolTravelDetail.getThirtyPrice());
			mSchoolTravelDetail.setMinFollowNumber(1);
			mSchoolTravelDetail.setMaxFollowNumber(30);
			break;
		case R.id.fourty_seat:
			setPriceLayout(R.id.fourty_seat, mSchoolTravelDetail.getFourPrice());
			mSchoolTravelDetail.setMinFollowNumber(31);
			mSchoolTravelDetail.setMaxFollowNumber(49);
			break;
		case R.id.fifty_seat:
			setPriceLayout(R.id.fifty_seat, mSchoolTravelDetail.getFiftyPrice());
			mSchoolTravelDetail.setMinFollowNumber(50);
			mSchoolTravelDetail.setMaxFollowNumber(Integer.MAX_VALUE);
			break;
		case R.id.qq_icon:
			String url = "mqqwpa://im/chat?chat_type=wpa&uin=" + mSchoolServiceDetail.getqq();
			startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
			break;
		case R.id.phone_icon:
			Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mSchoolServiceDetail.getPhone()));
			startActivity(intent);
			break;
		case R.id.date:
			Intent selectDateIntent = new Intent(SchoolTravelDetailActivity.this, SelectDateActivity.class);
			selectDateIntent.putExtra(SelectDateActivity.PRODUCT_DATE_DATA_LIST, mSchoolTravelDetail);
			startActivityForResult(selectDateIntent, QUEST_DATE_CODE);
			break;
		case R.id.place_next_btn:
			if (StringUtils.isEmpty(mDate)) {
				toast("请选择出团日期!");
				return;
			}
			Intent submitOrderIntent = new Intent(SchoolTravelDetailActivity.this, SubmitOrderActivity.class);
			mSchoolTravelDetail.setSelectPrice(mSelectPrice);
			submitOrderIntent.putExtra(SubmitOrderActivity.SCHOOL_TRAVLE_DETAIL, mSchoolTravelDetail);
			startActivity(submitOrderIntent);
			break;
		case R.id.outline:
			setmContentView(R.id.outline, mSchoolTravelDetail.getMessage());
			break;
		case R.id.cost:
			setmContentView(R.id.cost, mSchoolTravelDetail.getPriceMessage());
			break;
		case R.id.rule_description:
			setmContentView(R.id.rule_description, mSchoolTravelDetail.getRuleMessage());
			break;
		}
	}

	public void setmContentView(int viewID, String content) {
		mContentView.loadUrl(content);
		int footNavColor = getResources().getColor(R.color.foot_nav);
		int aboutText = getResources().getColor(R.color.about_text);

		mOutlineView.setTextColor(viewID == R.id.outline ? footNavColor : aboutText);
		mCostView.setTextColor(viewID == R.id.cost ? footNavColor : aboutText);
		mRuleDescriptionView.setTextColor(viewID == R.id.rule_description ? footNavColor : aboutText);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (RESULT_OK == resultCode && requestCode == QUEST_DATE_CODE) {
			mDate = data.getStringExtra(SelectDateActivity.DATE);
			mSchoolTravelDetail.setDateline(mDate);
			mDateBtn.setText("选择出团日期:   " + mDate);
		}
	}

	private IndicatorPagerAdapter adapter = new IndicatorViewPagerAdapter() {

		@Override
		public View getViewForTab(int position, View convertView, ViewGroup container) {
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.tab_guide, container, false);
			}
			return convertView;
		}

		@Override
		public View getViewForPage(int position, View convertView, ViewGroup container) {
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.image_show_layout, container, false);
			}
			((LifeqImageView) convertView.findViewById(R.id.image)).loadFile(mCoverImageUrlList.get(position),
					ImageType.SourceImage, null, null);
			return convertView;
		}

		@Override
		public int getCount() {
			return mCoverImageUrlList.size();
		}
	};

}
